package odgs.message.server;

import java.util.List;

import odgs.Connection;
import odgs.Contents;
import odgs.ContentsFile;
import odgs.Result;
import odgs.message.Message;
import odgs.message.MessageHandler;
import odgs.message.MessageProcessor;
import odgs.transaction.ContentsRemoveTransaction;

public class FileDeleteCompleteHandler implements MessageHandler
{
	public void execute(MessageProcessor processor, Message msg, Connection con)
	{
		ContentsFile file = (ContentsFile) msg.get("file");
		ContentsRemoveTransaction tran = (ContentsRemoveTransaction) msg.get("transaction");
		Contents cont = processor.getServerManager().getContents(file.getContentsUID());
		String ip = (String) msg.get("ip");
		Connection cons = processor.getNetworkManager().getConnection(ip);
		
		processor.getServerManager().freeStorage(file);

		Message reMsg = new Message(Message.CONTENTS_REMOVE_TRANSACTION_RESPONSE);
		List<ContentsFile> list = processor.getServerManager().getContentsFile(cont);
		if(list.size() == 0)
		{
			if(processor.getServerManager().removeContents(cont.getUid()) > 0)
			{
				reMsg.put("state", processor.getServerManager().getGridState());
				reMsg.put("transaction", tran);
				reMsg.setResult(Result.CONTENTS_REMOVED_OK);
				processor.getNetworkManager().broadcastMessage(reMsg);
			}
			else
			{
				reMsg.setResult(Result.CONTENTS_REMOVE_FAIL);
				reMsg.put("transaction", tran);
				cons.sendMessage(reMsg);
			}
		}
	}
}